package utils.extjs

/**
 * Compiler with groovy-minimal.jar 1.5.5+
 * Convert ext-menu.xml to json string which Ext TreePanel can identify.It's easier to implement with 
 * groovy GPath.
 * Auther:shawn.guo
 */
public class ExtTreeProviderFunctionAgent {

	public static String getJSONTree(String XMLTree,HashSet auths,String locale)
	{
	    String xmlMenu=XMLTree;
	    String jsonMenu="";
	
	    def rootNode = new XmlSlurper().parseText(xmlMenu);

	    //convert xmlmenu to jsonmenu
	    jsonMenu+=/[/;
	    for(node in rootNode.TreeNode)
	    {
	        def jsonFrag=ExtTreeProviderFunctionAgent.getJSONMenuByAuth(auths,locale,node);
	        if(jsonFrag!=null)
	            jsonMenu+=jsonFrag;
	    }
        //redundant comma
	    if(jsonMenu[jsonMenu.length()-1]!="[")
	    {
	        jsonMenu=jsonMenu[0..jsonMenu.length()-2]
	    }
	    jsonMenu+="]";

	    return jsonMenu;
	}

	public static String getJSONMenuByAuth(auths,locale, node)
	{
	    String jsonFrag="";

	     //security check,no permission then ignore the node generation.
	     boolean isAuthenticated=false;
	      if(node['@permission'].text()=="")
	          isAuthenticated=true;
	      else
	      {
	          node['@permission'].text().split(",").each{
	 	         if(auths.contains(it)) isAuthenticated=true;
	 	     }
	      }
	    
	     if(!isAuthenticated)
	         return null;
	        
	    jsonFrag+="{";
	    //Support for I18N menu
	    if(locale==null)
	    {
	         jsonFrag+=/"text":"/+node['@text'].text()+/",/
	    }
	    else
	    {
	         jsonFrag+=/"text":"/+node['@text_'+locale].text()+/",/
	    }
	        
	    jsonFrag+=/"id":"/+node['@id'].text()+/",/
	    jsonFrag+=/"leaf":/+node['@leaf'].text()+/,/
	    jsonFrag+=/"hrefTarget":"/+node.ExtProperties.hrefTarget.text()+/",/
	    jsonFrag+=/"singleClickExpand":true/+/,/
	    jsonFrag+=/"cls":"/+node.ExtProperties.cls.text()+/"/
	    if(node.ExtProperties.icon.text())
	    	jsonFrag+=/,"icon":"/+node.ExtProperties.icon.text()+/"/
	    
            //organize subMenu
	     if(node['@leaf'].text()=="false" && node.SubTreeNodes.size()!=0 && node.SubTreeNodes.TreeNode.size()!=0)
	     {
	         jsonFrag+=/,"children":[/;
	         for(subNode in node.SubTreeNodes.TreeNode)
	         {
	           		def subJsonFrag=ExtTreeProviderFunctionAgent.getJSONMenuByAuth(auths,locale,subNode);
	           		if(subJsonFrag!=null)
	           		     jsonFrag+=subJsonFrag;
	         }
	        //redundant comma
          	 if(jsonFrag[jsonFrag.length()-1]!="[")
    	    {
    	        jsonFrag=jsonFrag[0..jsonFrag.length()-2]
    	    }
    	    jsonFrag+="]";    
          }
          jsonFrag+="},"
	      return jsonFrag;

	    
	}
}